var KOC = require("koc.common.utils");
var CommonUtils = require("../common-utils");
var Redis = null;

var RedisCommon;

module.exports = RedisCommon = {
    //region 初始化
    Init: function (redis) {
        Redis = redis;
        return this;
    },
    //endregion
    //region ChannelUVListDay:广告渠道UV列表(天、PC)
    ChannelUVListDay: {
        Key: "ChannelUVListDay-" + KOC.Moment().format("YYMMDD"),
        Add: function (Value, callback) {
            Redis.pipeline([
                ["sadd", this.Key, Value],
                ["expireat", this.Key, KOC.Moment().add(1, "days").endOf("day").format("X")]
            ]).exec(function (err, result) {
                var retValue = KOC.ReturnValue.New();
                if (err || result[0][0]) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                }
                retValue.returnObject = result[0][1];
                callback(retValue);
            });
        }
    },
    //endregion
    //region ChannelIPListDay:广告渠道IP列表(天、PC)
    ChannelIPListDay: {
        Key: "ChannelIPListDay-" + KOC.Moment().format("YYMMDD"),
        Add: function (Value, callback) {
            Redis.pipeline([
                ["sadd", this.Key, Value],
                ["expireat", this.Key, KOC.Moment().add(1, "days").endOf("day").format("X")]
            ]).exec(function (err, result) {
                var retValue = KOC.ReturnValue.New();
                if (err || result[0][0]) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                }
                retValue.returnObject = result[0][1];
                callback(retValue);
            });
        }
    },
    //endregion
    //region PhoneAuthCode:手机验证码
    PhoneAuthCode: {
        Key: function (Phone) {
            return "PhoneAuthCode:" + Phone;
        },
        Get: function (Phone, callback) {
            var parm = {};
            parm.Key = this.Key(Phone);
            KOC.Async.series([
                //获取手机验证码
                function (callback) {
                    Redis.hmget(parm.Key, "CreateDate", "Count", function (err, result) {
                        if (err) {
                            callback(KOC.ReturnValue.New({
                                hasError: true,
                                message: err.message
                            }));
                            return;
                        }
                        if (!result[0]) {
                            callback();
                            return;
                        }
                        result[0] = KOC.Moment(new Date(result[0]));
                        if (KOC.Moment().diff(result[0], "seconds") < (CommonUtils.SMS.VerifyCode.Interval * 0.9)) {
                            callback(KOC.ReturnValue.New({
                                hasError: true,
                                message: CommonUtils.SMS.VerifyCode.Interval + "秒内只允许获取一次验证码"
                            }));
                            return;
                        }
                        parm.CountReset = KOC.Moment().format("YYYYMMDD") != result[0].format("YYYYMMDD");
                        if (!parm.CountReset && result[1] && KOC.StringUtils.ToIntPositive(result[1]) >= CommonUtils.SMS.VerifyCode.DayMax) {
                            callback(KOC.ReturnValue.New({
                                hasError: true,
                                message: "同一个手机号一天只能获取" + CommonUtils.SMS.VerifyCode.DayMax + "次验证码"
                            }));
                            return;
                        }
                        callback();
                    });
                },
                //写入手机验证码
                function (callback) {
                    parm.Code = KOC.Lodash.random(10000, 99999).toString();
                    Redis.pipeline([
                        ["hmset", parm.Key, {
                            Code: parm.Code,
                            Status: 0,
                            CreateDate: new Date()
                        }],
                        parm.CountReset ? ["hset", parm.Key, "Count", 1] : ["hincrby", parm.Key, "Count", 1],
                        ["expireat", parm.Key, KOC.Moment().add(2, "days").startOf("day").format("X")]
                    ]).exec(function (err) {
                        var retValue = KOC.ReturnValue.New();
                        if (err) {
                            retValue.hasError = true;
                            retValue.message = err.message;
                        } else {
                            retValue.returnObject = parm;
                        }
                        callback(retValue);
                    });
                }
            ], function (retValue) {
                callback(retValue);
            });
        },
        Check: function (Phone, Code, callback) {
            Phone = this.Key(Phone);
            var retValue = KOC.ReturnValue.New();
            Redis.hgetall(Phone, function (err, result) {
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                    callback(retValue);
                    return;
                }
                if (!result) {
                    retValue.hasError = true;
                    retValue.message = "验证码已过期,请重新获取";
                    callback(retValue);
                    return;
                }
                if (KOC.Moment().diff(KOC.Moment(new Date(result.CreateDate)), "minutes") > CommonUtils.SMS.VerifyCode.Expired) {
                    retValue.hasError = true;
                    retValue.message = "验证码已过期,有效期" + CommonUtils.SMS.VerifyCode.Expired + "分钟";
                    callback(retValue);
                    return;
                }
                if (result.Status != 0) {
                    retValue.hasError = true;
                    retValue.message = "验证码已被使用失效";
                    callback(retValue);
                    return;
                }
                if (result.Code !== Code) {
                    retValue.hasError = true;
                    retValue.message = "验证码错误";
                    callback(retValue);
                    return;
                }
                Redis.hset(Phone, "Status", 1);
                callback(retValue);
            });
        }
    },
    //endregion
    //region UserAnchorListHot:艺人热度列表(热度值)
    UserAnchorListHot: {
        Key: "UserAnchorListHot",
        Add: function (List, callback) {
            if (!KOC.Lodash.isArray(List)) {
                callback(KOC.ReturnValue.New({
                    hasError: true,
                    message: "传入参数错误[List]"
                }));
                return;
            }
            var _ValueList = [];
            KOC.Lodash.forEach(List, function (ThisValue, n) {
                try {
                    _ValueList.push(JSON.stringify(ThisValue));
                } catch (ex) {
                    _ValueList.push(ThisValue);
                }
            });
            var _Pipeline = [["del", this.Key]];
            if (_ValueList.length >= 1) {
                _Pipeline.push(["rpush", this.Key, _ValueList]);
            }
            Redis.pipeline(_Pipeline).exec(function (err) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                }
                callback(retValue);
            });
        },
        Get: function (Start, Length, callback) {
            if (typeof Start === "function") {
                callback = Start;
                Start = 0;
                Length = -1;
            } else if (typeof Length === "function") {
                callback = Length;
                Length = -1;
            }
            Start = KOC.StringUtils.ToIntPositive(Start);
            Length = KOC.StringUtils.ToInt(Length, -1);
            Redis.lrange(this.Key, Start, Start + (Length > 0 ? Length - 1 : Length), function (err, result) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                    callback(retValue);
                    return;
                }
                retValue.returnObject = [];
                KOC.Lodash.forEach(result, function (ThisValue) {
                    try {
                        retValue.returnObject.push(JSON.parse(ThisValue));
                    } catch (ex) {
                    }
                });
                callback(retValue);
            });
        }
        // GetRandom: function (Length, Value, callback) {
        //     // if (typeof Rate === "function") {
        //     //     callback = Rate;
        //     //     Rate = 50;
        //     // }
        // },
    },
    //endregion
    //region UserAnchorListNew:艺人新秀列表(热度值)
    UserAnchorListNew: {
        Key: "UserAnchorListNew",
        Add: function (List, callback) {
            if (!KOC.Lodash.isArray(List)) {
                callback(KOC.ReturnValue.New({
                    hasError: true,
                    message: "传入参数错误[List]"
                }));
                return;
            }
            var _ValueList = [];
            KOC.Lodash.forEach(List, function (ThisValue) {
                try {
                    _ValueList.push(JSON.stringify(ThisValue));
                } catch (ex) {
                    _ValueList.push(ThisValue);
                }
            });
            var _Pipeline = [["del", this.Key]];
            if (_ValueList.length >= 1) {
                _Pipeline.push(["rpush", this.Key, _ValueList]);
            }
            Redis.pipeline(_Pipeline).exec(function (err) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                }
                callback(retValue);
            });
        },
        Get: function (Start, Length, callback) {
            if (typeof Start === "function") {
                callback = Start;
                Start = 0;
                Length = -1;
            } else if (typeof Length === "function") {
                callback = Length;
                Length = -1;
            }
            Start = KOC.StringUtils.ToIntPositive(Start);
            Length = KOC.StringUtils.ToInt(Length, -1);
            Redis.lrange(this.Key, Start, Start + (Length > 0 ? Length - 1 : Length), function (err, result) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                    callback(retValue);
                    return;
                }
                retValue.returnObject = [];
                KOC.Lodash.forEach(result, function (ThisValue) {
                    try {
                        retValue.returnObject.push(JSON.parse(ThisValue));
                    } catch (ex) {
                    }
                });
                callback(retValue);
            });
        }
    },
    //endregion
    //region GiftUserRankingWeek:礼物用户周排行
    GiftUserRankingWeek: {
        Key: function (Type, Gift_ID) {
            //Type G:送出人 R:接收人
            return "GiftUserRankingWeek-" + KOC.Moment().startOf("week").format("YYMMDD") + "-" + Type + "-" + Gift_ID;
        },
        Add: function (Value, callback) {
            Value = KOC.Lodash.extend({
                Gift_ID: null,
                User_ID: null,
                User_ID_Gift: null,
                Num: null
            }, Value);
            Value.Gift_ID = KOC.StringUtils.ToIntPositive(Value.Gift_ID);
            Value.User_ID = KOC.StringUtils.ToIntPositive(Value.User_ID);
            Value.User_ID_Gift = KOC.StringUtils.ToIntPositive(Value.User_ID_Gift);
            Value.Num = KOC.StringUtils.ToIntPositive(Value.Num);
            if (!Value.Gift_ID) {
                callback(KOC.ReturnValue.New({
                    hasError: true,
                    message: "参数错误[Gift_ID]"
                }));
                return;
            }
            if (!Value.User_ID && !Value.User_ID_Gift) {
                callback(KOC.ReturnValue.New({
                    hasError: true,
                    message: "参数错误[User_ID & User_ID_Gift]"
                }));
                return;
            }
            if (!Value.Num) {
                callback(KOC.ReturnValue.New({
                    hasError: true,
                    message: "参数错误[Num]"
                }));
                return;
            }
            var _Pipeline = [];
            if (Value.User_ID) {
                _Pipeline.push(["zincrby", this.Key("G", Value.Gift_ID), Value.Num, Value.User_ID]);
                _Pipeline.push(["expireat", this.Key("G", Value.Gift_ID), KOC.Moment().add(10, "days").format("X")]);
            }
            if (Value.User_ID_Gift) {
                _Pipeline.push(["zincrby", this.Key("R", Value.Gift_ID), Value.Num, Value.User_ID_Gift]);
                _Pipeline.push(["expireat", this.Key("R", Value.Gift_ID), KOC.Moment().add(10, "days").format("X")]);
            }
            Redis.pipeline(_Pipeline).exec(function (err) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                }
                callback(retValue);
            });
        },
        AddForReset: function (Type, List, callback) {
            if (!KOC.Lodash.includes(["G", "R"], Type)) {
                callback(KOC.ReturnValue.New({
                    hasError: true,
                    message: "传入参数错误[Type]"
                }));
                return;
            }
            if (!KOC.Lodash.isArray(List)) {
                callback(KOC.ReturnValue.New({
                    hasError: true,
                    message: "传入参数错误[List]"
                }));
                return;
            }
            var _Pipeline = [];
            var _Gift_ID;
            KOC.Lodash.forEach(List, function (ThisValue) {
                if (_Gift_ID !== ThisValue.Gift_ID) {
                    if (_Gift_ID) {
                        _Pipeline.push(["expireat", RedisCommon.GiftUserRankingWeek.Key(Type, _Gift_ID), KOC.Moment().add(10, "days").format("X")]);
                    }
                    _Pipeline.push(["del", RedisCommon.GiftUserRankingWeek.Key(Type, ThisValue.Gift_ID)]);
                    _Gift_ID = ThisValue.Gift_ID;
                }
                _Pipeline.push(["zincrby", RedisCommon.GiftUserRankingWeek.Key(Type, ThisValue.Gift_ID), ThisValue.Num, ThisValue.User_ID]);
            });
            Redis.pipeline(_Pipeline).exec(function (err) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                }
                callback(retValue);
            });
        },
        GetList: function (Value, callback) {
            Value = KOC.Lodash.extend({
                Type: null,
                Gift_ID: null,
                Start: null,
                Length: null
            }, Value);
            Value.Start = KOC.StringUtils.ToIntPositive(Value.Start);
            Value.Length = KOC.StringUtils.ToIntPositive(Value.Length) || 100;
            Value.Length = Value.Length > 100 ? 100 : Value.Length;//最多取100条
            Redis.zrevrange(this.Key(Value.Type, Value.Gift_ID), Value.Start, Value.Start + Value.Length - 1, "withscores", function (err, result) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                    callback(retValue);
                    return;
                }
                retValue.returnObject = [];
                for (var i = 0; i < result.length; i = i + 2) {
                    retValue.returnObject.push({
                        User_ID: KOC.StringUtils.ToIntPositive(result[i]),
                        Gift_Num: KOC.StringUtils.ToIntPositive(result[i + 1])
                    });
                }
                callback(retValue);
            });
        }
    },
    //endregion


    //region UserAnchorApply:用户艺人申请
    UserAnchorApply: {
        Key: function (User_ID) {
            return "UserAnchorApply:" + User_ID;
        },
        StepOne: function (Value, callback) {
            Value = KOC.Lodash.extend({
                User_ID: null,
                Sex: null,
                RealName: null,
                Phone: null,
                QQ: null,
                Email: null,
                Tags: null,
                Network: null,
                Family_ID: null
            }, Value);
            Value.Key = this.Key(Value.User_ID);
            //写入输入
            Redis.pipeline([
                ["hmset", Value.Key, {
                    Sex: Value.Sex,
                    RealName: Value.RealName,
                    Phone: Value.Phone,
                    QQ: Value.QQ,
                    Email: Value.Email,
                    Tags: Value.Tags,
                    Network: Value.Network,
                    Family_ID: Value.Family_ID
                }],
                ["expire", Value.Key, 60 * 60]
            ]).exec(function (err) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                } else {
                    retValue.returnObject = Value;
                }
                callback(retValue);
            });
        },
        StepTwo: function (Value, callback) {
            Value = KOC.Lodash.extend({
                User_ID: null,
                Account_RealName: null,
                Account_CardNo: null,
                Account_BankFullName: null,
                Account_Province: null,
                Account_City: null,
                Account_BankName: null,
                IDCard: null
            }, Value);
            Value.Key = this.Key(Value.User_ID);
            //写入输入
            Redis.pipeline([
                ["hmset", Value.Key, {
                    Account_RealName: Value.Account_RealName,
                    Account_CardNo: Value.Account_CardNo,
                    Account_BankFullName: Value.Account_BankFullName,
                    Account_Province: Value.Account_Province,
                    Account_City: Value.Account_City,
                    Account_BankName: Value.Account_BankName,
                    IDCard: Value.IDCard
                }],
                ["expire", Value.Key, 60 * 60]
            ]).exec(function (err) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                } else {
                    retValue.returnObject = Value;
                }
                callback(retValue);
            });
        },
        Get: function (User_ID, callback) {
            Redis.hgetall(this.Key(User_ID), function (err, result) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                    callback(retValue);
                    return;
                }
                if (!result) {
                    retValue.hasError = true;
                    retValue.message = "数据过期请重新申请";
                    callback(retValue);
                    return;
                }
                retValue.returnObject = result;
                callback(retValue);
            });
        }
    },
    //endregion
    //region UserFamilyApply:用户公会申请
    UserFamilyApply: {
        Key: function (User_ID) {
            return "UserFamilyApply:" + User_ID;
        },
        StepOne: function (Value, callback) {
            Value = KOC.Lodash.extend({
                User_ID: null,
                ContactName: null,
                Family_Name: null,
                Phone: null,
                QQ: null,
                Email: null
            }, Value);
            Value.Key = this.Key(Value.User_ID);
            //写入输入
            Redis.pipeline([
                ["hmset", Value.Key, {
                    ContactName: Value.ContactName,
                    Family_Name: Value.Family_Name,
                    Phone: Value.Phone,
                    QQ: Value.QQ,
                    Email: Value.Email
                }],
                ["expire", Value.Key, 60 * 60]
            ]).exec(function (err) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                } else {
                    retValue.returnObject = Value;
                }
                callback(retValue);
            });
        },
        StepTwo: function (Value, callback) {
            Value = KOC.Lodash.extend({
                User_ID: null,
                Account_RealName: null,
                Account_CardNo: null,
                Account_BankFullName: null,
                Account_Province: null,
                Account_City: null,
                Account_BankName: null,

                IDCard: null
            }, Value);
            Value.Key = this.Key(Value.User_ID);
            //写入输入
            Redis.pipeline([
                ["hmset", Value.Key, {
                    Account_RealName: Value.Account_RealName,
                    Account_CardNo: Value.Account_CardNo,
                    Account_BankFullName: Value.Account_BankFullName,
                    Account_Province: Value.Account_Province,
                    Account_City: Value.Account_City,
                    Account_BankName: Value.Account_BankName,
                    IDCard: Value.IDCard
                }],
                ["expire", Value.Key, 60 * 60]
            ]).exec(function (err) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                } else {
                    retValue.returnObject = Value;
                }
                callback(retValue);
            });
        },
        Get: function (User_ID, callback) {
            Redis.hgetall(this.Key(User_ID), function (err, result) {
                var retValue = KOC.ReturnValue.New();
                if (err) {
                    retValue.hasError = true;
                    retValue.message = err.message;
                    callback(retValue);
                    return;
                }
                if (!result) {
                    retValue.hasError = true;
                    retValue.message = "数据过期请重新申请";
                    callback(retValue);
                    return;
                }
                retValue.returnObject = result;
                callback(retValue);
            });
        }
    }
    //endregion
};